<template>
  <el-card>
    <!-- default-expand-all 可以控制展开所有节点 ，但是学习一些有难度的 -->
    <el-tree ref="treeRef" node-key="id" :default-expanded-keys="expandIds" :default-checked-keys="checkedIds"
      :data="menuList" :props="treeConfig" show-checkbox></el-tree>

    <div>
      <el-button type="primary" @click="save">保存</el-button>
    </div>
  </el-card>
</template>
<script setup lang='ts'>
import { getAllMenuApi, getRoleMenusListApi } from '@/api'
import { ref } from 'vue';
import { useRoute } from 'vue-router';
import { ElTree } from 'element-plus'
const menuList = ref<IMenuModel[]>([])
let expandIds = ref<number[]>([]);

getAllMenuApi().then(res => {
  if (res.code == 200) {
    menuList.value = res.data;
    expandIds.value = res.data.map(item => item.id);
  }
})

const treeConfig = {
  chidlren: 'children',
  label: 'title',
}

// 根据roldId 获取 当前角色的现有菜单
// 获取 roleId
const rotue = useRoute()
const roleId = Number(rotue.params.id as string);
let checkedIds = ref<number[]>([]);
if (roleId) {
  getRoleMenusListApi(roleId).then(res => {
    if (res.code == 200) {
      checkedIds.value = res.data.map(item => item.id);
    }
  })
}

const treeRef = ref<InstanceType<typeof ElTree>>();

const save = () => {
  console.log(treeRef.value?.getCheckedKeys());
}
</script>
<style lang="less" scoped></style>